<template>
  <div class="min-h-full bg-gray-50 p-6">
    <!-- 顶部操作区域 -->
    <!-- 顶部操作区域 -->
    <div class="mb-6 rounded-lg bg-white p-4 shadow-sm">
      <div class="flex flex-nowrap items-center justify-between">
        <div class="flex items-center whitespace-nowrap">
          <span class="mr-3 text-gray-600">抵押天数：</span>
          <el-input v-model="mortgageDays" class="w-60 min-w-[200px]" placeholder="请输入抵押天数" type="number" :min="10"
            :max="30" @blur="(e) => validateMortgageDays((e.target as HTMLInputElement).value)" />
        </div>
        <el-button type="primary" size="large" class="ml-4 w-32" @click="handleSubmitOrder">
          提交订单
        </el-button>
      </div>
    </div>

    <!-- 订单卡片 -->
    <el-card class="flex-1 overflow-hidden rounded-lg transition-shadow duration-300 hover:shadow-md" shadow="never">
      <template #header>
        <div class="flex flex-wrap items-center gap-4">
          <h2 class="text-lg font-medium text-gray-800">订单列表</h2>
          <div class="flex flex-wrap items-center gap-3">
            <el-tag type="success" effect="dark" class="flex items-center px-3 py-1.5">
              总金额: ¥{{ dataList[0]?.orderTotalPrice?.toFixed(2) || '0.00' }}
            </el-tag>
            <el-tag type="warning" effect="dark" class="flex items-center px-3 py-1.5">
              <span>保管费: ¥{{ n?.toFixed(2) || '0.00' }}</span>
              <el-tooltip content="保管费 = 抵押价格 × 0.01 × 抵押天数" placement="top">
                <el-icon class="ml-1.5">
                  <QuestionFilled />
                </el-icon>
              </el-tooltip>
            </el-tag>
          </div>
        </div>
      </template>

      <!-- 表格部分 -->
      <el-table :data="dataList" v-loading="loading" class="w-full">
        <el-table-column prop="imageUrl" label="图片" width="100">
          <template #default="scope">
            <el-image :src="scope.row.imageUrl || '/assets/imgs/touxiang.jpg'" :preview-src-list="[scope.row.imageUrl]"
              fit="contain" class="h-12 w-12 rounded object-cover" />
          </template>
        </el-table-column>
        <!-- 表格列的修改 -->
        <el-table-column prop="jewelryName" :width="260" label="名称" class-name="whitespace-nowrap" />
        <el-table-column prop="abrade" label="磨损" width="100" class-name="whitespace-nowrap">
          <template #default="scope">
            <span class="text-gray-600 whitespace-nowrap">{{ scope.row.abrade }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="maxToBuyPrice" label="求购最高价">
          <template #default="scope">
            <span class="text-emerald-600">¥{{ scope.row.maxToBuyPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="mortgagePrice">
          <template #header>
            <div class="flex items-center">
              <span>抵押价格</span>
              <el-tooltip content="抵押价格 = 最高求购价 × 抵押比例" placement="top">
                <el-icon class="ml-1.5">
                  <QuestionFilled />
                </el-icon>
              </el-tooltip>
            </div>
          </template>
          <template #default="scope">
            <span class="font-medium text-blue-600">
              ¥{{ scope.row.mortgagePrice }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="mortgageRatio" label="抵押比例" width="100">
          <template #default="scope">
            <el-tag size="small" effect="plain">
              {{ scope.row.mortgageRatio }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { QuestionFilled } from '@element-plus/icons-vue'
interface ValuationItem {
  imageUrl: string
  jewelryName: string
  wear: number
  maxToBuyPrice: number
  mortgagePrice: number
  mortgageRatio: number
  mortgageDays: number
  orderTotalPrice: number
}

interface ValuationResponse {
  data: ValuationItem[]
}
const { showLoading, hideLoading } = useLoading()
definePageMeta({
  title: '订单管理',
  showInMenu: false,
  requiresAuth: true,
  layout: 'back',
  icon: 'icon-order'
})
const router = useRouter()
const mortgageDays = ref(0)
const dataList = ref<ValuationItem[]>([])
const route = useRoute()
const valuationData = JSON.parse(route.params.data as string)
showLoading()
const { data } = await useCustomFetch<ValuationResponse>('/api/order/valuation', {
  method: 'POST',
  body: valuationData,
  withToken: true
})
dataList.value = data.value?.data || []
hideLoading()
const n = computed(() => dataList?.value[0]?.orderTotalPrice * 0.01 * mortgageDays.value)
// 状态和分页相关的响应式数据
const loading = ref(false)

// 获取订单列表数据



// 添加验证函数
const validateMortgageDays = (value: string | number) => {
  const num = Number(value)
  if (num < 10 || num > 30 || !Number.isInteger(num)) {
    mortgageDays.value = 10
    $message('抵押天数必须是10-30之间的整数', 'warning')
  }
}



// 提交订单
const handleSubmitOrder = () => {
  if (mortgageDays.value <= 0 || mortgageDays.value > 30) {
    $message('抵押天数必须是10-30之间的整数', 'warning')
    return
  }
  ElMessageBox.confirm(
    '确认提交新订单？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      try {
        showLoading()
        let data = dataList.value.map(el => ({
          ...el,
          mortgageDays: mortgageDays.value,
          totalStorageFee: n.value
        }))
        const response = await customFetch<{
          data: any,
          code: string
        }>('/api/order/createOrder', {
          method: 'POST',
          body: data,
          isLoading: false
        })
        console.log(response);
        if (response.data == 'success') {
          ElMessage({
            type: 'success',
            message: '订单提交成功'
          })
          router.go(-1)
        } else {
          ElMessage({
            type: 'error',
            message: '订单提交失败'
          })
        }
        // 刷新订单列表
      } catch (error) {
        console.error('提交订单失败:', error)
      } finally {
        hideLoading()
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消提交'
      })
    })
}


</script>

<style scoped>
/* 仅保留必要的自定义样式 */
:deep(.el-card__body) {
  @apply flex-1 flex flex-col;
}

:deep(.el-table th) {
  @apply bg-gray-50 font-medium;
}

:deep(.el-input__wrapper) {
  @apply shadow-none border border-gray-300 hover:border-blue-400 transition-colors duration-300;
}

:deep(.el-table__row:hover > td) {
  @apply bg-gray-50;
}
</style>